package com.brozers.islamdini;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TimeDataSource {

  // Database fields
  private SQLiteDatabase database;
  private TimeSQLiteHelper dbHelper;
  private String[] allColumns = { TimeSQLiteHelper.COLUMN_ID,TimeSQLiteHelper.COLUMN_CITY_ID,
		  TimeSQLiteHelper.COLUMN_PRAYERTIME,TimeSQLiteHelper.COLUMN_DAYOFYEAR,TimeSQLiteHelper.COLUMN_DAY,
		  TimeSQLiteHelper.COLUMN_MONTH};

  public TimeDataSource(Context context) {
    dbHelper = new TimeSQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public Time createTime(String cityID,String prayertime,String dayofyear,String day,String month) {
    ContentValues values = new ContentValues();
    values.put(TimeSQLiteHelper.COLUMN_CITY_ID, cityID);
    values.put(TimeSQLiteHelper.COLUMN_PRAYERTIME, prayertime);
    values.put(TimeSQLiteHelper.COLUMN_DAYOFYEAR, dayofyear);
    values.put(TimeSQLiteHelper.COLUMN_DAY, day);
    values.put(TimeSQLiteHelper.COLUMN_MONTH, month );
    long insertId = database.insert(TimeSQLiteHelper.TABLE_TIMES, null,
        values);
    Cursor cursor = database.query(TimeSQLiteHelper.TABLE_TIMES,
        allColumns, TimeSQLiteHelper.COLUMN_ID + " = " + insertId, null,
        null, null, null);
    cursor.moveToFirst();
    Time newTime = cursorToTime(cursor);
    cursor.close();
    return newTime;
  }

  public void deleteTime(Time time) {
    long id = time.getId();
    System.out.println("Comment deleted with id: " + id);
    database.delete(TimeSQLiteHelper.TABLE_TIMES, TimeSQLiteHelper.COLUMN_ID
        + " = " + id, null);
  }

  public List<Time> getAllTime() {
    List<Time> comments = new ArrayList<Time>();

    Cursor cursor = database.query(TimeSQLiteHelper.TABLE_TIMES,
        allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Time comment = cursorToTime(cursor);
      comments.add(comment);
      cursor.moveToNext();
    }
    // Make sure to close the cursor
    cursor.close();
    return comments;
  }

  private Time cursorToTime(Cursor cursor) {
    Time comment = new Time();
    comment.setId(cursor.getLong(0));
    comment.setCityId(cursor.getString(1));
    comment.setPrayertimes(cursor.getString(2));
    comment.setDayofyear(cursor.getString(3));
    comment.setDay(cursor.getString(4));
    comment.setMonth(cursor.getString(5));
    return comment;
  }
} 
